package br.com.dts.prompt
{

	public class Prompt
	{

		public var functions:Object;

		public function Prompt(functions:Object=null)
		{
			if (!functions)
			{
				this.functions={};
			}
			else
			{
				this.functions=functions;
			}
		}

		public function execute(command:String):Object
		{
			var ret:Object=null;

			var tokens:Array=returnTokens(command);
			var funcName:String=tokens[0];
			tokens.splice(0, 1);

			try
			{
				ret=this.functions[funcName]["apply"](null, tokens);
			}
			catch (err:Error)
			{
				throw new Error("Function called do not exists");
			}

			return ret;
		}

		private function returnTokens(command:String):Array
		{
			var ret:Array=new Array();
			var array:Array=command.split(" ");

			for (var i:uint=0; i < array.length; i++)
			{
				if (array[i].substr(0, 1) == "\"")
				{
					var item:String=array[i].substring(1, array[i].length);

					if (item.substr(item.length - 1, 1) == "\"")
					{
						item=item.substring(0, item.length-1);
						ret.push(item);
						continue;
					}

					for (i=i + 1; i < array.length; i++)
					{
						if (array[i].substr(array[i].length - 1, 1) == "\"")
						{
							item+=" " + array[i].substr(0, array[i].length - 1);

							ret.push(item);
							break;
						}
						else
						{
							item+=" " + array[i];
						}
					}
				}
				else
				{
					ret.push(array[i]);
				}
			}

			return ret;
		}

	}
}
